//
//  MyAddressViewController.m
//  jingjing2.0
//
//  Created by apple on 16/5/10.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "MyAddressViewController.h"
#import "MyAddressTableViewCell.h"
#import "AddNewAddressViewController.h"
#import "SubmitOrderViewController.h"
@interface MyAddressViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSInteger _selectedBtn;
}
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataSource;
@end

@implementation MyAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"我的收取地址";
    self.view.backgroundColor=[UIColor whiteColor];
    _dataSource=[NSMutableArray array];
    [self setUpTableView];
    

}
#pragma mark--创建表
-(void)setUpTableView
{
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight) style:UITableViewStylePlain];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    [_tableView registerNib:[UINib nibWithNibName:@"MyAddressTableViewCell" bundle:nil] forCellReuseIdentifier:@"address"];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tableView];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count+1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return 50;
    }else
    {
        return 80;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        UITableViewCell *cell=[_tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        cell.imageView.image=nil;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.imageView.image=[UIImage imageNamed:@"add_new_action"];
        cell.imageView.bounds=CGRectMake(0, 0, 20, 20);
        cell.textLabel.text=@"新增收取地址";
        cell.textLabel.textColor=BLUECOLOR;
        return cell;
    }else
    {
        MyAddressTableViewCell *address=[_tableView dequeueReusableCellWithIdentifier:@"address" forIndexPath:indexPath];
        //防重用
        
        address.noUserAddress.image=nil;
        address.isCasual.text=nil;
        address.isCasual.backgroundColor=nil;
        address.isSelectedBtn.image=nil;
        address.selectionStyle=UITableViewCellSelectionStyleNone;
        AddressData *data=self.dataSource[indexPath.section-1];
        address.name.text=[data.ReceiveName stringByRemovingPercentEncoding];
        address.phoneNumber.text=[data.Mobile stringByRemovingPercentEncoding];
        address.address.text=[NSString stringWithFormat:@"%@%@%@%@",[data.CityName stringByRemovingPercentEncoding],
        [data.AreaName stringByRemovingPercentEncoding],
        [data.LocateAddress stringByRemovingPercentEncoding],
        [data.DetailAddress stringByRemovingPercentEncoding]];
        //是否是从地址管理界面push进来的
        if (_isAddressManager) {
            address.isSelectedBtn.hidden=YES;
        }else
        {
            address.isSelectedBtn.hidden=NO;
            
            //是否从订单界面push进来
            if (!_currentAddress) {
                //默认第一个为选中状态
                if (indexPath.section==1) {
                    address.isSelectedBtn.image=[UIImage imageNamed:@"pay_true"];
                  
                    _selectedBtn=indexPath.section;
                }else
                {
                    address.isSelectedBtn.image=[UIImage imageNamed:@"co_voal_bg"];

                }
            }else
            {
                //如果是从订单界面进来，使选中的地址打勾
                if ([address.address.text isEqualToString:_currentAddress]) {
                    address.isSelectedBtn.image=[UIImage imageNamed:@"pay_true"];
                    
                    _selectedBtn=indexPath.section;
                }else
                {
                    address.isSelectedBtn.image=[UIImage imageNamed:@"co_voal_bg"];
                    
                }
            }
            //是否是常用默认地址
            if ([data.IsDefault isEqualToString:@"1"]) {
                address.isCasual.text=@"常用";
                address.isCasual.backgroundColor=BLUECOLOR;
            }
            //判断地址是否可用
            if (![address.address.text hasPrefix:CURRENTCITY]) {
                address.noUserAddress.hidden=NO;
                address.noUserAddress.image=[UIImage imageNamed:@"no_user_address"];
                address.moreBtn.hidden=YES;
                address.moreBtn.enabled=NO;
                address.isSelectedBtn.hidden=YES;
            }else
            {
                address.moreBtn.hidden=NO;
                address.moreBtn.enabled=YES;
                address.noUserAddress.hidden=YES;
               address.isSelectedBtn.hidden=NO;
                [address.moreBtn setBackgroundImage:[UIImage imageNamed:@"address_menu_icon"] forState:UIControlStateNormal];
            }
        }
            return address;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section==0) {
        return 10;
    }
    return 0;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        AddNewAddressViewController *addressData=[[AddNewAddressViewController alloc]init];
        addressData.categoryID=self.categoryID;
        addressData.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:addressData animated:YES];
    }else
    {
        if (_isAddressManager) {
            //只能编辑
        }else
        {
            MyAddressTableViewCell *address=[_tableView cellForRowAtIndexPath:indexPath];
            MyAddressTableViewCell *selected=[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:_selectedBtn]];

            if (![address.address.text hasPrefix:CURRENTCITY])
            {

                return;
            }else
            {
                selected.isSelectedBtn.image=[UIImage imageNamed:@"co_voal_bg"];
                address.isSelectedBtn.image=[UIImage imageNamed:@"pay_true"];
                                _selectedBtn=indexPath.section;
                //判断该地址是否符合范围
                AddressData *data=self.dataSource[indexPath.section-1];
                [self selectedAddressIsAvailableWithModel:data];
            }
            
        }
       
    }
}
#pragma mark--判断选择的地址是否符合范围
-(void)selectedAddressIsAvailableWithModel:(AddressData *)data
{
   //http://192.168.1.135:3722/Common/IsServiceAreaV2
    //m_IsServiceAreaV2Para(CategoryID,CityCode,AddressId,Timestamp,Sign)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString *timeStamp=[GeneralTool gettimestamp];
    NSDictionary *dic=@{@"CategoryID":self.categoryID,
                        @"CityCode":data.CityCode,
                        @"AddressId":data.AddressId,
                        @"Timestamp":timeStamp,
                        };
    NSString *sign=[GeneralTool GetSin:dic];
    NSDictionary *dataDic=@{@"CategoryID":self.categoryID,
                            @"CityCode":data.CityCode,
                            @"AddressId":data.AddressId,
                            @"Timestamp":timeStamp,
                            @"Sign":sign};
    NSDictionary *reqestDic=@{@"m_IsServiceAreaV2Para":dataDic};
    [RequestTool requestDataWithType:@"post" andUrlString:[NSString stringWithFormat:@"Common/IsServiceAreaV2"] andParameters:reqestDic andRequestFinished:^(id responses, NSError *error)
    {
        [MBProgressHUD hideHUDForView:self.view];
        if (error) {
            [MBProgressHUD showError:@"连接服务器失败，请检查网络"];
        }else
        {
            if ([responses[@"IsSuccess"]intValue]==1) {
                if ([[responses[@"ReturnString"]stringByRemovingPercentEncoding]isEqualToString:@"在服务范围"]) {
                    //返回，并传值
                    if (_passDataBlock) {
                        _passDataBlock(data);
                    }
                    NSArray *arr=self.navigationController.viewControllers;
                    [arr enumerateObjectsUsingBlock:^(UIViewController * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        if ([obj isKindOfClass:[SubmitOrderViewController class]]) {
                            [self.navigationController  popToViewController:obj animated:YES];
                        }
                    }];
                   
                }else
                
                {
                    [MBProgressHUD showError:[responses[@"ReturnString"]stringByRemovingPercentEncoding]];
                }
            }
        }
        
    }];
}
#pragma mark--进来和出去的一些设置
-(void)viewWillAppear:(BOOL)animated
{
    _selectedBtn=1;
    [super viewWillAppear:animated];
    [GeneralTool hideTabBar];
    [GeneralTool getMyAddressListWithIsDefault:@"MORE" andReuqestBlock:^(id response, NSError *error) {
        if (error) {
            [MBProgressHUD showError:@"请求超时"];
        }else
        {
            if([response[@"IsSuccess"]intValue]==1)
            {
                NSArray *Arr=response[@"ReturnObject"];
                [self.dataSource removeAllObjects];
                if (Arr.count>0) {
                    for (NSDictionary *dic in Arr) {
                        AddressData *data=[[AddressData alloc]initWithDic:dic];
                        [self.dataSource addObject:data];
                    }
                    [_tableView reloadData];
                }
            }
        }
    }];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [GeneralTool showTabBar];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
